import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const mobile = searchParams.get('mobile')
    const name = searchParams.get('name')
    const userId = searchParams.get('user_id')
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const skip = (page - 1) * limit

    // 构建查询条件
    const where: any = {
      delete_time: 0 // 只查询未删除的用户
    }

    if (userId) {
      where.id = parseInt(userId)
    }

    if (mobile) {
      where.mobile = {
        contains: mobile
      }
    }

    if (name) {
      where.name = {
        contains: name
      }
    }

    // 查询用户列表和总数
    const [users, total] = await Promise.all([
      prisma.smoke_user.findMany({
        where,
        select: {
          id: true,
          mobile: true,
          cc: true,
          name: true,
          avatar: true,
          gender: true,
          age: true,
          height: true,
          weight: true,
          create_time: true,
          last_active_time: true,
          city: true,
          // 统计用户的健康记录数量 - 移除此项以优化性能
          // _count: {
          //   select: {
          //     healthLogs: true
          //   }
          // }
        },
        orderBy: {
          create_time: 'desc'
        },
        skip,
        take: limit
      }),
      prisma.smoke_user.count({ where })
    ])

    // 格式化用户数据
    const formattedUsers = users.map(user => ({
      id: Number(user.id),
      mobile: user.mobile,
      cc: user.cc,
      name: user.name,
      avatar: user.avatar,
      gender: user.gender,
      age: user.age,
      height: user.height,
      weight: user.weight,
      city: user.city,
      healthLogsCount: 0, // 不再从数据库获取，设置为默认值 0
      createTime: user.create_time ? new Date(user.create_time * 1000).toISOString() : null,
      lastActiveTime: user.last_active_time ? new Date(user.last_active_time * 1000).toISOString() : null
    }))

    return NextResponse.json({
      success: true,
      data: {
        users: formattedUsers,
        pagination: {
          page,
          limit,
          total,
          pages: Math.ceil(total / limit)
        }
      },
      message: '用户列表获取成功'
    })
  } catch (error) {
    console.error('Users query error:', error)
    return NextResponse.json({
      success: false,
      error: 'Database query failed',
      message: '用户查询失败'
    }, { status: 500 })
  }
}